import { DefaultStage } from "../default-stage";
import { RawAssetsName, RawAssetsUrl } from "../../raw-assets-info";
import { Debug } from "babylon-lib/gui/control/debug";
import { Quaternion, Vector3 } from "@babylonjs/core/Maths/math";
import '@babylonjs/core/Collisions/collisionCoordinator';
import { Helper } from "babylon-lib/tool/helper";
import { AbstractControl } from "babylon-lib/gui/control/abstract-control";
import { GravityRoaming } from "babylon-lib/preset/gravity-roaming";
import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder";
import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial";
import { WebXRFeatureName } from "@babylonjs/core/XR/webXRFeaturesManager";


class GenerateComponent {
    public static initialize(stage: DefaultStage): void {
        this.setModel(stage);
        this.testDebug(stage);
        this.initializeMovement(stage);
    }

    private static initializeMovement(stage: DefaultStage): void {
        const scene = stage.mainScene;
        Helper.setSceneMesh(scene, 'isPickable', false, [AbstractControl.namePostfix]);
        Helper.setSceneMesh(scene, 'checkCollisions', false);
        const roaming = new GravityRoaming(scene, {
            floorMeshKey: RawAssetsName.ground,
            obstacleMeshKey: RawAssetsName.bound,
            autoUpdate: true,
            gravity: new Vector3(0, -9.8 / 60, 0),
        });
    }

    private static setModel(stage: DefaultStage): void {
        const scene = stage.mainScene;
        const loader = stage.loader(scene);
        const model = loader.getMeshTaskInfo(RawAssetsUrl.changjing)?.loadedMeshes!;
        const texture = loader.getTextureTaskInfo(RawAssetsUrl.textureMarker)?.texture!;

        const marker = MeshBuilder.CreatePlane('marker-mesh', { size: 1 }, stage.mainScene);
        const material = new StandardMaterial('marker-material', stage.mainScene);
        material.diffuseTexture = texture;
        marker.material = material;
        marker.rotationQuaternion = Quaternion.FromEulerAngles(1.5708, 3.1416, 0);

        model.forEach(m => {
            m.isVisible = false;
        });

        try {
            stage.ar?.featuresManager.enableFeature(WebXRFeatureName.IMAGE_TRACKING, 'latest', {
                images: [{
                    src: texture.url,
                    estimatedRealWorldWidth: 0.2,
                }]
            });
        } catch (err) {
            console.warn(err);
        }
        console.log(stage.ar?.featuresManager.getEnabledFeatures());
    }

    private static testDebug(stage: DefaultStage): void {
        Debug.initialize(stage.mainScene, {
            scattered: true,
            offset: new Vector3(2, 0, 0),
            lockToCamera: true
        });

        // AnimationFrame.request(()=>{
        //     Debug.log('FPS:',stage.engine.performanceMonitor.averageFPS);
        // },1000,1200,{});
    }

}

export { GenerateComponent };
